package ar.com.spsolutions.splibrary.services;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import ar.com.spsolutions.splibrary.services.exception.ServiceException;
import ar.com.spsolutions.splibrary.user.User;

public class PasswordUtils {

	public void encript(final User user) {
		final String password = user.getPassword();
		user.setPassword(this.encript(password));
	}

	public boolean validate(final User user, final String password) {
		return user.getPassword().equals(this.encript(password));
	}

	private String encript(final String password) {
		final byte[] defaultBytes = password.getBytes();
		MessageDigest algorithm;
		final byte[] messageDigest;
		try {
			algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(defaultBytes);
			messageDigest = algorithm.digest();

			final StringBuffer hexString = new StringBuffer();
			for (final byte element : messageDigest) {
				hexString.append(Integer.toHexString(0xFF & element));
			}
			return hexString.toString();
		} catch (final NoSuchAlgorithmException e) {
			throw new ServiceException(e);
		}
	}

}
